#!/usr/bin/env python
# encoding: utf-8

from lib import upload_photos
from lib.get_faces_urls import GetFacesUrls
from lib import common
import sys
import os.path
import logging
import urllib2

"http://picasaweb.google.com/lh/nameTagPaging"

def DownloadFile(url, filename):
  logging.info("Downloading '%s' to '%s" % (url, filename))
  open(filename, "w").write(urllib2.urlopen(url).read())

def main():
  source_photos = sys.argv[1]
  destination = sys.argv[2]
  
  uploader = upload_photos.PhotoUploader()
  uploader.UploadPath(source_photos)
  file_map = dict(map(lambda entry: (entry[0], os.path.basename(entry[1])), uploader.file_map.iteritems()))
  
  logging.info("Querying clusterView")
  request = urllib2.Request('http://picasaweb.google.com/lh/clusterView',
                            headers={'Cookie': common.Cookie()})
  urllib2.urlopen(request).read()
  
  faces_urls = GetFacesUrls()
  for photo_id, url in faces_urls.iteritems():
    if photo_id in file_map:
      DownloadFile(url, os.path.join(destination, file_map[photo_id]))
  
if __name__ == '__main__':
	main()

